import { LoadingOutlined, PlusOutlined } from "@ant-design/icons";
import { request } from "@umijs/max";
import { Upload, message } from "antd";
import { forwardRef, useImperativeHandle, useRef, useState } from "react";

export async function upload(
    data: FormData,
    options?: { [key: string]: any },
) {
    return request<{
        code: number;
        data: Record<string, any>;
        msg?: string;
    }>('/api/v1/oss_file/upload', {
        method: 'POST',
        data,
        ...(options || {}),
    });
}

const CustomImgUpload = (props: any, ref: any) => {
    const [imageUrl, setImageUrl] = useState<string>();
    const [imgLoading, setLoading] = useState(false);

    const uploadButton = (
        <button style={{ border: 0, background: 'none' }} type="button">
            {imgLoading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>上传图片</div>
        </button>
    );

    // console.log(props);
    const beforeUpload = (file: any) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('您只能上传JPG/PNG文件! ');
        }
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isLt2M) {
            message.error('图像必须小于10MB! ');
        }
        return isJpgOrPng && isLt2M;
    };


    let fileList: any[] | undefined = []
    if (props.value) {
        fileList = [props.value]
    } else {
        if (imageUrl) {
            fileList = [{
                url: imageUrl
            }]
        }
    }
    // console.log('fileList', fileList, imageUrl);

    useImperativeHandle(ref, () => ({
    }))

    return <Upload.Dragger
        fileList={fileList}
        // onChange={props?.onChange}
        listType="picture-card"
        showUploadList={false}
        beforeUpload={beforeUpload}
        customRequest={async (file) => {
            try {
                const formData = new FormData()
                formData.append("file", file.file)
                formData.append("type", props.type ||'banner')
                const res = await upload(formData)
                // console.log(res);
                setImageUrl(res.data?.url)
                // console.log(props);
                props?.onChange?.(res.data)
                // console.log(imgKeyMapRef, res.data);

                setLoading(false)
            } catch (e) {
                setLoading(false)
            }
        }}
        className='custom_img_upload'
        style={props.style}
    
    >
        {props.value ? <img src={props.value?.url} style={{ width: '100%' }}  alt={''}/> : uploadButton}
    </Upload.Dragger>
}

export default forwardRef(CustomImgUpload)